<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="会计科目编码" prop="subjectCode" label-width="110px">
              <el-input v-model="queryParams.subjectCode" placeholder="请输入科目编码" clearable @keyup.enter="handleQuery" style="width: 160px" />
            </el-form-item>
            <el-form-item label="会计科目名称" prop="subjectName" label-width="110px">
              <el-input v-model="queryParams.subjectName" placeholder="请输入科目名称" @keyup.enter="handleQuery" style="width: 160px" />
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="queryParams.state" placeholder="全部" clearable style="width: 160px">
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['budget:accountSubject:add']"> 新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['budget:accountSubject:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        border
        ref="subjectRef"
        v-loading="loading"
        :data="accountSubjectList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpandAll"
        :style="tableStyle"
        class="enhanced-table"
      >
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <el-table-column label="上级科目" align="center" prop="parentId" v-if="false" />
        <el-table-column label="会计科目名称" prop="subjectName" show-overflow-tooltip min-width="180" />
        <!--        <el-table-column label="排序" prop="orderNum" width="100" align="center"/>-->
        <el-table-column label="状态" align="center" prop="state" width="140">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="300" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="200" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['budget:accountSubject:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['budget:accountSubject:add']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['budget:accountSubject:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"-->
      <!--                  v-model:limit="queryParams.pageSize" @pagination="getList" />-->
    </el-card>
    <!-- 添加或修改会计科目管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" style="width: 700px" append-to-body>
      <el-form ref="accountSubjectFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级科目 " prop="parentId" label-width="120px">
          <el-tree-select
            v-model="form.parentId"
            :data="subjectOptions"
            :props="{ value: 'id', label: 'subjectName', children: 'children' }"
            value-key="id"
            placeholder="请选择上级科目"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="会计科目编码 " prop="subjectCode" label-width="120px">
          <el-input v-model="form.subjectCode" placeholder="请输入会计科目编码" :disabled="dialog.title === '修改会计科目'" />
        </el-form-item>
        <el-form-item label="会计科目名称 " prop="subjectName" label-width="120px">
          <el-input v-model="form.subjectName" placeholder="请输入会计科目名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum" label-width="120px">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态 " prop="state" label-width="120px">
          <el-radio-group v-model="form.state">
            <el-radio :value="'0'">正常</el-radio>
            <el-radio :value="'1'">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注 " prop="remark" label-width="120px">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" show-word-limit maxlength="500" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AccountSubject" lang="ts">
import { addAccountSubject, delAccountSubject, getAccountSubject, listAccountSubject, updateAccountSubject } from '@/api/budget/accountSubject';
import { AccountSubjectForm, AccountSubjectQuery, AccountSubjectVO } from '@/api/budget/accountSubject/types';
import { useTableHeight } from '@/hooks/useMethod';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const accountSubjectList = ref<AccountSubjectVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);

const subjectOptions = ref<AccountSubjectVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const accountSubjectFormRef = ref<ElFormInstance>();

const isExpandAll = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AccountSubjectForm = {
  id: undefined,
  parentId: undefined,
  subjectCode: undefined,
  subjectName: undefined,
  state: '0',
  remark: undefined,
  orderNum: 0
};

const queryParams = ref<AccountSubjectQuery>({
  subjectCode: undefined,
  subjectName: undefined,
  state: undefined
});

const rules = {
  subjectCode: [{ required: true, message: '会计科目编码不能为空', trigger: 'blur' }],
  subjectName: [{ required: true, message: '会计科目名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '排序不能为空', trigger: 'change' }]
};

const form = ref<AccountSubjectForm>(initFormData);

/** 查询会计科目管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAccountSubject(queryParams.value);
  accountSubjectList.value = res.data;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  accountSubjectFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 科目树形下拉框*/
const listParams = ref<AccountSubjectQuery>({
  state: '0' //正常
});

const getTreeSelect = async () => {
  subjectOptions.value = [];
  const subject: AccountSubjectVO = { id: 0, subjectName: '主科目', children: [] };
  const res = await listAccountSubject(listParams.value);
  subject.children = res.data;
  subjectOptions.value.push(subject);
};

/** 新增按钮操作 */
const handleAdd = (row?: AccountSubjectVO) => {
  reset();
  getTreeSelect();
  row && row.id ? (form.value.parentId = row.id) : (form.value.parentId = 0);
  dialog.visible = true;
  dialog.title = '添加会计科目';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AccountSubjectVO) => {
  reset();
  await getTreeSelect();
  const _id = row?.id || ids.value[0];
  const res = await getAccountSubject(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改会计科目';
};

/** 提交按钮 */
const submitForm = () => {
  accountSubjectFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAccountSubject(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAccountSubject(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AccountSubjectVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除该数据项？').finally(() => (loading.value = false));
  await delAccountSubject(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'budget/account/export',
    {
      ...queryParams.value
    },
    `会计科目.xlsx`
  );
};
const tableStyle = useTableHeight(showSearch);
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped></style>
